import {
  ProFormDateRangePicker,
  ProFormDigit,
  ProFormTimePicker,
  ProTable,
} from '@ant-design/pro-components';
import {
  Button,
  Popconfirm,
  message,
  Tag,
  Upload,
  Image,
  Table,
  Space,
  Breadcrumb,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import type { UploadProps } from 'antd';
import {
  UploadOutlined,
  PlusOutlined,
  FileSearchOutlined,
} from '@ant-design/icons';
import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import ImportExcel from '@/pages/LabManage/component/ImportExcel';
import { useBoolean } from 'ahooks';

import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import moment from 'moment';

export default () => {
  const formRef = useRef<ProFormInstance>();
  const editformRef = useRef<ProFormInstance>();
  const [selectRow, { toggle }] = useBoolean(false);

  const updateStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({ annexPath: info.file.response.data });
        editformRef.current?.setFieldsValue({
          annexPath: info.file.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  //获取 开放课题 列表
  const findAllOpenTopic = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openTopic/findAllOpenTopic`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result) => {
        // result.map((e: any) => {
        //   result.map((g: any) => {
        //     g.year = e.year + '';
        //   });
        // });
      },
    },
  );
  //新增 开放课题
  const insertOpenTopic = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openTopic/insertOpenTopic`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //删除 开放课题
  const delOpenTopic = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openTopic/delOpenTopic`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //编辑 开放课题
  const updateOpenTopic = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/openTopic/updateOpenTopic`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const getLike = useRequest((data = { field: 'technicalName' }) => {
    return {
      url: 'http://10.1.40.84:9993/getLike',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  const confirm = (e: any) => {
    delOpenTopic.run({ id: e.id }).then(() => {
      findAllOpenTopic.run();
      message.success('删除成功');
    });
  };
  const cancel = (e: any) => {
    message.error('已取消');
  };
  const columns: any = [
    {
      align: "center",
      title: '序号',
      dataIndex: 'seq',
      key: 'seq',
      // copyable: true,
      hideInSearch: true,
      width: 50,
    },
    {
      title: '开放年份',
      align: "center",
      dataIndex: 'year',
      key: 'year',
      hideInSearch: true,
      // render: (text: any, record: any, index: any) => {
      //   return record?.year;
      // },
      sorter: {
        compare: (a: any, b: { year: any }) => a.year < b.year,
      },
      width: 100,
    },
    {
      title: '开放年份',
      align: "center",
      dataIndex: 'year',
      key: 'year',
      valueType: 'dateYear',
      hideInTable: true,
    },
    {
      title: '课题名称',
      align: "center",
      dataIndex: 'topicName',
      key: 'topicName',
      width: 200,
      // copyable: true,
      // ellipsis: true,
    },
    {
      title: '负责人',
      align: "center",
      dataIndex: 'director',
      key: 'director',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '负责人工作单位',
      align: "center",
      dataIndex: 'workUnit',
      key: 'workUnit',
      hideInSearch: true,
    },
    {
      title: '开始时间',
      align: "center",
      dataIndex: 'startTime',
      key: 'startTime',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      align: "center",
      dataIndex: 'endTime',
      key: 'endTime',
      hideInSearch: true,
    },
    {
      title: '总经费(万元)',
      align: "center",
      dataIndex: 'totalFund',
      key: 'totalFund',
      hideInSearch: true,
      width: 70,
    },
    {
      title: '本年度经费(万元)',
      align: "center",
      dataIndex: 'yearFund',
      key: 'yearFund',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '报道链接',
      align: "center",
      dataIndex: 'reportLink',
      key: 'reportLink',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.reportLink !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              查看链接
            </a>
          );
        } else {
          return <span>暂无链接</span>;
        }
      },
    },
    {
      title: '材料',
      align: "center",
      dataIndex: 'annexPath',
      key: 'annexPath',
      hideInSearch: true,
      width: '140px',
      render: (text: any, record: any) => {
        if (record.annexPath !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              下载
            </a>
          );
        } else {
          return <span>暂无材料</span>;
        }
      },
    },
    // {
    //   title: '审核情况',
    //   key: 'isPass',
    //   dataIndex: 'isPass',
    //   hideInSearch: true,
    //   width: '8%',
    //   render: (text: any, record: any, index: any) => {
    //     switch (text) {
    //       case 0:
    //         return '未通过(待上传文件)';
    //       case 1:
    //         return '未审核';
    //       case 2:
    //         return '审核通过';
    //       case 3:
    //         return '审核失败';
    //     }
    //   },
    // },
    {
      title: '操作',
      align: "center",
      key: 'option',
      width: 120,
      fixed: 'right',
      valueType: 'option',
      render: (text: any, record: any) => [
        <ModalForm
          title="编辑调研"
          trigger={<a key="1">编辑</a>}
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            updateOpenTopic.run(values).then(() => {
              message.info('编辑成功！');
              findAllOpenTopic.run();
            });
            return true;
          }}
          initialValues={{ ...record, year: record.year + '' }}
          key="1"
          formRef={editformRef}
          grid={true}
        >
          <ProForm.Group>
            <ProFormText name="id" hidden />
            <ProFormDatePicker.Year
              name="year"
              label="年份"
              colProps={{ span: 4 }}
            />
            <ProFormText
              name="topicName"
              label="课题名称"
              colProps={{ span: 8 }}
              rules={[{ required: true, message: '请输入' }]}
            />
            <ProFormText
              name="director"
              label="负责人"
              colProps={{ span: 4 }}
              rules={[{ required: true, message: '请输入' }]}
            />
            <ProFormText
              name="workUnit"
              label="负责人工作单位"
              colProps={{ span: 8 }}
              rules={[{ required: true, message: '请输入' }]}
            />
            <ProFormSelect
              name="authorsJobLevel"
              label="负责人职称等级"
              options={[
                { label: '正高级', value: '正高级' },
                { label: '副高级', value: '副高级' },
                { label: '中级', value: '中级' },
                { label: '初级', value: '初级' },
                { label: '其他', value: '其他' },
              ]}
              rules={[{ required: true, message: '请输入' }]}
              fieldProps={{
                onChange: (e) => {
                  getLike.run({ field: 'technicalName', level: e });
                },
              }}
              colProps={{ span: 6 }}
            />
            <ProFormSelect
              colProps={{ span: 6 }}
              name="authorsJobTitle"
              label="负责人职称名称"
              options={getLike.data}
            />
            <ProFormDateRangePicker
              fieldProps={{
                picker: 'month',
                format: 'YYYY-MM',
              }}
              colProps={{ span: 8 }}
              name="time"
              label="开始时间-结束时间"
              rules={[{ required: true, message: '请选择' }]}
            />
            {/* <ProFormDatePicker.Month

              colProps={{ span: 4 }}
              name="startTime"
              label="开始时间"
            />
            <ProFormDatePicker.Month
              colProps={{ span: 4 }}
              name="endTime"
              label="结束时间"
            /> */}
            <ProFormDigit
              colProps={{ span: 4 }}
              name="totalFund"
              label="总经费(万元)"
              rules={[{ required: true, message: '请输入' }]}
            />
            <ProFormText
              colProps={{ span: 18 }}
              name="authors"
              label="参与人员"
              tooltip="除负责人外的其他参与人员,多人请用,（英文半角逗号）分隔"
            />
            <ProFormDigit
              colProps={{ span: 6 }}
              name="yearFund"
              label="本年度经费(万元)"
              rules={[{ required: true, message: '请输入' }]}
            />
            <ProFormText width="xl" name="reportLink" label="报道链接" />
            <ProFormDatePicker name="annexPath" hidden />
            <Upload {...props}>
              <Button
                icon={<UploadOutlined />}
                type="link"
                style={{ marginTop: 30 }}
              >
                上传材料（上传会议照片，以会议名称命名）
              </Button>
            </Upload>
          </ProForm.Group>
        </ModalForm>,
        <Popconfirm
          key={'2'}
          title="确定删除吗？"
          onConfirm={() => confirm(record)}
          onCancel={() => cancel}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const Refresh = () => {
    findAllOpenTopic.run();
  };

  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>合作交流</Breadcrumb.Item>
            <Breadcrumb.Item>开放课题</Breadcrumb.Item>
          </Breadcrumb>
        ),
        extra: [
          ],
      }}
    >
      <ProTable
        columns={columns}
        dataSource={findAllOpenTopic?.data}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
          pageSize: 10,
        }}
        onSubmit={(e: any) => {
          findAllOpenTopic.run(e);
        }}
        onReset={() => {
          findAllOpenTopic.run();
        }}
        loading={findAllOpenTopic.loading}
        headerTitle={<strong>开放课题列表</strong>}
        options={false}
        // scroll={{ x: 'calc(800px + 50%)' }}
        toolBarRender={() => [
          <ImportExcel key="1" tableName={'OPEN_TOPIC'} Refresh={Refresh} />,
          <Button
            key="2"
            type="primary"
            onClick={() => {
              window.open(
                'http://10.1.40.84:9993/file/model/OPEN_TOPIC_模板.xlsx ',
              );
            }}
          >
            下载模版
          </Button>,

          <ModalForm
            title={
              <>
                <PlusOutlined />
                <strong>{'新增开放课题'}</strong>
              </>
            }
            trigger={
              <Button
                key="primary"
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => getLike.run()}
              >
                新增开放课题
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              console.log(values);
              insertOpenTopic.run(values).then(() => {
                findAllOpenTopic.run();
                message.info('添加成功！');
              });
              return true;
            }}
            key="1"
            grid={true}
            formRef={formRef}
          >
            <ProForm.Group>
              <ProFormText name="id" hidden />
              <ProFormDatePicker.Year
                name="year"
                label="年份"
                colProps={{ span: 4 }}
              />
              <ProFormText
                name="topicName"
                label="课题名称"
                colProps={{ span: 8 }}
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText
                name="director"
                label="负责人"
                colProps={{ span: 4 }}
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText
                name="workUnit"
                label="负责人工作单位"
                colProps={{ span: 8 }}
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormSelect
                name="authorsJobLevel"
                label="负责人职称等级"
                rules={[{ required: true, message: '请输入' }]}
                options={[
                  { label: '正高级', value: '正高级' },
                  { label: '副高级', value: '副高级' },
                  { label: '中级', value: '中级' },
                  { label: '初级', value: '初级' },
                  { label: '其他', value: '其他' },
                ]}
                fieldProps={{
                  onChange: (e) => {
                    getLike.run({ field: 'technicalName', level: e });
                  },
                }}
                colProps={{ span: 6 }}
              />
              <ProFormSelect
                colProps={{ span: 6 }}
                name="authorsJobTitle"
                label="负责人职称名称"
                options={getLike.data}
              />

              <ProFormDateRangePicker
                fieldProps={{
                  picker: 'month',
                  format: 'YYYY-MM',
                }}
                colProps={{ span: 8 }}
                name="time"
                label="开始时间-结束时间"
                rules={[{ required: true, message: '请选择' }]}
              />
              {/* <ProFormDatePicker.Month
                colProps={{ span: 4 }}
                name="startTime"
                label="开始时间"
                rules={[{ required: true, message: '请选择' }]}
              />
              <ProFormDatePicker.Month
                colProps={{ span: 4 }}
                name="endTime"
                label="结束时间"
                rules={[{ required: true, message: '请选择' }]}
              /> */}
              <ProFormDigit
                colProps={{ span: 4 }}
                name="totalFund"
                label="总经费(万元)"
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText
                colProps={{ span: 18 }}
                name="authors"
                label="参与人员"
                tooltip="除负责人外的其他参与人员,多人请用,（英文半角逗号）分隔"
              />

              <ProFormDigit
                colProps={{ span: 6 }}
                name="yearFund"
                label="本年度经费(万元)"
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText width="xl" name="reportLink" label="报道链接" />

              <ProFormDatePicker name="annexPath" hidden />
              <Upload {...props}>
                <Button
                  icon={<UploadOutlined />}
                  type="link"
                  style={{ marginTop: 30 }}
                >
                  上传材料（上传会议照片，以会议名称命名）
                </Button>
              </Upload>
            </ProForm.Group>
          </ModalForm>,
        ]}
        search={{ labelWidth: 'auto' }}
        rowSelection={
          selectRow
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              }
            : false
        }
        tableAlertOptionRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={16}>
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'OPEN_TOPIC',
                    ids: selectedRowKeys,
                    status: 2, //审核通过
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllOpenTopic.run();
                  });
              }}
            >
              审核通过
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'OPEN_TOPIC',
                    ids: selectedRowKeys,
                    status: 3, //拒绝
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllOpenTopic.run();
                  });
              }}
            >
              拒绝
            </a>
          </Space>
        )}
      />
    </PageContainer>
  );
};
